const fs = require("fs");
const path = require("path");
const joi = require("joi");

// 确保日志文件夹存在
const logDirectory = path.join(__dirname, "../../../logs");
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

const logStream = fs.createWriteStream(path.join(logDirectory, "errors.log"), { flags: "a" });

const errorHandler = (err, req, res, next) => {
	let statusCode = 500;
	let errorMessage = "Internal Server Error";

	try {
		// Joi验证错误
		if (err instanceof joi.ValidationError) {
			statusCode = 400;
			errorMessage = "Validation Error";
			errorDetails = err.details.map(detail => detail.message).join(", ");
		}
		// 身份认证错误
		else if (err.name === "UnauthorizedError") {
			statusCode = 401;
			errorMessage = "Unauthorized. Please login.";
		}
		// 数据库错误
		else if (err.name === "SequelizeDatabaseError" || err.name === "MongoError") {
			statusCode = 500;
			errorMessage = "Database Error";
			errorDetails = err.message;
		}
		// 文件系统错误
		else if (err.code === "ENOENT") {
			statusCode = 404;
			errorMessage = "File or directory not found";
		}
		// 超时错误
		else if (err.code === "ETIMEDOUT") {
			statusCode = 408;
			errorMessage = "Request Timeout";
		}
		// 处理其他自定义业务错误
		else if (err.isBusinessLogic) {
			statusCode = err.statusCode || 500;
			errorMessage = err.message;
		}

		// 未知错误详细信息只在开发环境返回
		if (process.env.NODE_ENV !== "production") {
			errorMessage += ` Error detail: ${err.stack}`;
		}

		// 日志记录未知错误
		if (!err.isHandled) {
			const errorLog = `[${new Date().toISOString()}] ${err.stack || err}\n`;

			// 向控制台记录错误
			console.error(errorLog);

			// 写入错误日志文件
			logStream.write(errorLog);
		}
	} catch (handlerError) {
		// 错误处理器也有可能抛出错误
		const errorLog = `[${new Date().toISOString()}] Error within the error handler: ${handlerError.stack || handlerError}\n`;

		// 向控制台记录错误处理器的错误
		console.error(errorLog);

		// 写入错误处理器的错误日志文件
		logStream.write(errorLog);
	}

	res.status(statusCode).json({
		status: statusCode,
		message: errorMessage
	});
};

module.exports = errorHandler;